<template>
  <div class="lwq-collapse">
      <slot></slot>
  </div>
</template>
<script setup lang="ts">
import { provide, ref, watch } from 'vue';
import type { CollapseEmits, CollapseProps, NameType } from './types';
import { collapseContextKey } from './types';

defineOptions({
  name: 'LwqCollapse'
});
const props = defineProps<CollapseProps>();
const emits = defineEmits<CollapseEmits>();
const activeNames = ref<NameType[]>([]);
watch(props.modelValue, () => {
  activeNames.value = props.modelValue;
})
if (props.accordion && activeNames.value.length > 1) {
  console.warn('accordion mode should only have one acitve item')
}
const handleItemClick = (item: NameType) => {

  if (props.accordion) {
    activeNames.value = [activeNames.value[0] === item ? '' : item ]
  } else {
    const index = activeNames.value.indexOf(item);
    if (index > -1) {
      // 存在，删除数组对应的一项
      activeNames.value.splice(index, 1);
    } else {
      // 不存在,插入对应的name
      activeNames.value.push(item);
    }
  }

  emits('update:modelValue', activeNames.value);
  emits('change', activeNames.value)
}
// 要让子组件知道那些item是被激活的,因为使用的是slot,没法传递,所以使用Provide/inject
provide(collapseContextKey, {
  activeNames,
  handleItemClick
});
</script>
<style scoped>
@import './style.css';
</style>